package cn.jdemo.pattern.builder.custom;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * setter属性值，build模式处理
 *
 * @date 2021/1/27
 */
public class Builder<T> {

    private final Supplier<T> instance;

    private List<Consumer<T>> lists= new ArrayList<>();

    public Builder(Supplier<T> instance){
        this.instance = instance;
    }

    public static <T> Builder<T> of(Supplier<T> instance){
        return new Builder<>(instance);
    }

    public  <P> Builder<T> with(CustomFunc<T,P> customFunc, P p1){
        Consumer<T> consumer = instance -> customFunc.setMethod(instance, p1);
        lists.add(consumer);
        return this;
    }

    public T build(){
        T value = instance.get();
        lists.stream().forEach(method -> {method.accept(value);});
        lists.clear();
        return value;
    }

    @FunctionalInterface
    interface CustomFunc<T,P>{
        void setMethod(T t,P p);
    }
}
